package com.campus.backend.service;

import cn.hutool.crypto.digest.MD5;
import com.campus.common.constants.GlobalConstant;
import com.campus.common.exception.BusinessException;
import com.campus.backend.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class SessionService {

	private Logger logger = LoggerFactory.getLogger(SessionService.class);

	@Autowired
	private RedisService redisService;

	public UserInfoVo getUserInfo() {
		String token = getToken();
		if(StringUtils.isBlank(token)){
			logger.warn("token is null");
			throw new BusinessException(8001,"Please log in and try again!");
		}
		UserInfoVo userInfo = redisService.getFromJson(token, UserInfoVo.class);
		if (userInfo == null) {
			logger.warn("get user info failed, token: " + token);
			throw new BusinessException(8001,"Please log in and try again!");
		}
		return userInfo;
	}

	public String getToken() {
		return getHeaderValue("token");
	}

	public String getHeaderValue(String key) {
		HttpServletRequest httpServletRequest = getRequest();
		return httpServletRequest.getHeader(key);
	}

	public HttpServletRequest getRequest() {
		ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
		if (servletRequestAttributes != null) {
			return servletRequestAttributes.getRequest();
		}
		return null;
	}

	public HttpServletResponse getResponse() {
		ServletRequestAttributes servletRequestAttributes = getServletRequestAttributes();
		if (servletRequestAttributes != null) {
			return servletRequestAttributes.getResponse();
		}
		return null;
	}

	private ServletRequestAttributes getServletRequestAttributes() {
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		if (requestAttributes == null) {
			return null;
		}
		if (requestAttributes instanceof ServletRequestAttributes) {
			return (ServletRequestAttributes) requestAttributes;
		}
		return null;
	}

	public String getMd5Password(String password, String salt){
		MD5 md5 = MD5.create();
		return md5.digestHex(md5.digestHex(password) + GlobalConstant.passStr + salt);
	}

}
